'use strict';

const { Service } = require('ee-core');
const Storage = require('ee-core/storage');
const _ = require('lodash');
const path = require('path');

/**
 * json数据存储
 * @class
 */
class JsondbService extends Service {

  constructor (ctx) {
    super(ctx);

    // jsondb数据库
    this.jsonFile = 'leno_admin';
    this.demoDB = Storage.connection(this.jsonFile);  
      // gongzuoleixing_table2
      // jiaoyanguize_table
      // shebei_table2
      // shebeifenzu_table
      // shebeileixing_table    
    this.lenoDBKey = {
      test_data: 'test_data',
      jiaoyanjieguo_table: 'jiaoyanjieguo_table',
      gongzuoleixing_table2: 'gongzuoleixing_table2',
      jiaoyanguize_table: 'jiaoyanguize_table',
      shebei_table2: 'shebei_table2',
      shebeifenzu_table: 'shebeifenzu_table',
      shebeileixing_table: 'shebeileixing_table',
      leno_user: 'leno_user',
      sys_dept: 'sys_dept',
    };
  }
  checkParam ({tableName,action}) {    
    if (tableName == 'jiaoyanjieguo_table') {
      return true
    }
    // 目前只能对jiaoyanjieguo_table进行修改，其他表数据只可以读取查看
    if (['get','getAll','getDataDir','getDataDir','batchAdd'].includes(action)) {
      return true
    }
    return false
  }
  /*
   * 增 Test data
   */
  async addTestData(addParam,tableName = 'test_data') {
    const key = this.lenoDBKey[tableName];
    if (!this.demoDB.db.has(key).value()) {
      this.demoDB.db.set(key, []).write();
    }
    
    const data = this.demoDB.db
    .get(key)
    .push(addParam)
    .write();

    return data;
  }
  /*
   * 批量添加
   */
  async batchAddTestData(batchAddParam,tableName = 'test_data',Overlay = false) {
    const key = this.lenoDBKey[tableName];
    if (!this.demoDB.db.has(key).value()) {
      this.demoDB.db.set(key, []).write();
    }
    // 如果是覆盖模式，则要把之前数据清空
    if (Overlay) {
      this.demoDB.db.set(key, []).write();
    }
    let allData = []
    batchAddParam.forEach(addParam => {
      let data = this.demoDB.db
      .get(key)
      .push(addParam)
      .write();
      allData.push(data)
    })
    return allData;
  }

  /*
   * 删 Test data
   */
  async delTestData(delParam,tableName = 'test_data') {
    const key = this.lenoDBKey[tableName];
    const data = this.demoDB.db
    .get(key)
    .remove({...delParam})
    .write();

    return data;
  }
  /*
   * 批量删除 Test data
   */
  async batchDelTestData(batchDelParam = [],tableName = 'test_data') {
    const key = this.lenoDBKey[tableName];
    const deleteData = []
    batchDelParam.forEach(del => {      
      const data = this.demoDB.db
      .get(key)
      .remove({...del})
      .write();
      deleteData.push(data)
    })

    return deleteData;
  }

  /*
   * 改 Test data
   */
  async updateTestData({findParam,updateData},tableName = 'test_data') {
    const key = this.lenoDBKey[tableName];
    const data = this.demoDB.db
    .get(key)
    .find({...findParam}) // 修改找到的第一个数据，貌似无法批量修改 todo
    .assign({...updateData})
    .write();

    return data;
  }

  /*
   * 查 Test data
   */
  async getTestData(searchParam,tableName = 'test_data') {
    const key = this.lenoDBKey[tableName];
    let data = this.demoDB.db
    .get(key)
    .find(searchParam) // 查找单个
    // .filter(function(o) {
    //   let isHas = true;
    //   isHas = age === o.age ? true : false;
    //   return isHas;
    // })
    //.orderBy(['age'], ['name']) 排序
    //.slice(0, 10) 分页
    .value();

    if (_.isEmpty(data)) {
      data = []
    }

    return data;
  }

  /*
   * all Test data
   */
  async getAllTestData(searchParam = {},tableName = 'test_data') {
    const key = this.lenoDBKey[tableName];
    if (!this.demoDB.db.has(key).value()) {
      this.demoDB.db.set(key, []).write();
    }
    let data = this.demoDB.db
    .get(key)
    .filter(function(o) {
      let isHas = true;
      Object.keys(searchParam).forEach(key => {
        if (searchParam[key] && !o[key].includes(searchParam[key])) {
          isHas = false
        }
      })
      return isHas;
    })    
    .value();

    if (_.isEmpty(data)) {
      data = []
    }

    return data;
  }

  /*
   * get data dir (sqlite)
   */
  async getDataDir() {
    const dir = this.demoDB.getStorageDir();    

    return dir;
  } 

  /*
   * set custom data dir (sqlite)
   */
  async setCustomDataDir(dir) {
    if (_.isEmpty(dir)) {
      return;
    }

    // the absolute path of the db file
    const dbFile = path.join(dir, this.jsonFile);
    this.demoDB = Storage.connection(dbFile);    

    return;
  }  
}

JsondbService.toString = () => '[class JsondbService]';
module.exports = JsondbService;
